/* MethodCall.cs -- 
   Copyright (C) 2008  Casey Marshall.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.  */


using System;
using SexpSharp;

namespace SexpSharp.RPC
{
	public sealed class MethodCall
	{
		private string name;
		private IValue[] args;

		public MethodCall(string name, IValue[] args)
		{
			if (name.Length == 0)
				throw new ArgumentException("must be a nonempty string", "name");
			this.name = name;
			this.args = args;
		}

		public MethodCall(Expression expr)
		{
			List list = expr as List;
			if (list == null)
				throw new ArgumentException("must be a list", "expr");
			if (list.Count < 2 || !(list.First is Atom) || !(list.Second is Atom))
				throw new ArgumentException("list must start with two atoms");
			if (list.First.ToString() != "method-call")
				throw new ArgumentException("list must begin with 'method-call'");
			this.name = list.Second.ToString();
			args = new IValue[list.Count - 2];
			int i = 0;
			foreach (Expression e in list.Rest.Rest)
			{
				args[i++] = Values.ExpressionToValue(e);
			}
		}

		public string Name
		{
			get { return name; }
		}

		public IValue[] Args
		{
			get { return args; }
		}

		public Expression ToExpression()
		{
			List list = new List();
			list.Add(new Atom("method-call"));
			list.Add(new Atom(name));
			if (args != null)
				foreach (IValue val in args)
					list.Add(val.ToExpression());
			return list;
		}
	}
}